package com.wjw.java.io.buffered_;

import java.io.*;

/**
 * 使用BufferedWriter写入数据,
 * 使用BufferedReader、BufferedWriter拷贝文件数据,边读边写入
 * ---------------------------------------------------------
 * 注:BufferedReader、BufferedWriter是用来操作字符的,
 * 不要用他们操作二进制文件,否则会造成文件的损坏
 */
public class BufferedWriter_ {
    public static void main(String[] args) {
        writeData();
        copyFile();
    }

    //1.写入数据
    public static void writeData(){
        //文件路径
        String filePath = "f:\\IO\\test_buffered_writer.txt";
        BufferedWriter bw = null;
        try {
            //bw = new BufferedWriter(new FileWriter(filePath));
            bw = new BufferedWriter(new FileWriter(filePath,true));
            bw.write("你好啊,BufferedWriter!!!");
            bw.newLine();//换行
            bw.write("123456");
            bw.newLine();//换行
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //这里只需关闭BufferedWriter,它的底层会去关闭传入的FileWriter
            try {
                if(bw != null){
                    bw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //2.拷贝文件数据,边读边写入
    public static void copyFile(){
        //源文件
        String srcFilePath = "f:\\IO\\test_buffered_reader.txt";
        //将源文件中的数据拷贝的目标文件中
        String destFilePath = "f:\\IO\\test_buffered_copy.txt";
        BufferedReader br = null;
        BufferedWriter bw = null;
        String line = "";
        try {
            br = new BufferedReader(new FileReader(srcFilePath));
            bw = new BufferedWriter(new FileWriter(destFilePath));
            //循环读取文件
            while ((line = br.readLine()) != null){
                bw.write(line);//写入数据
                bw.newLine();//换行
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(bw != null){
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(br != null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
